
<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index === levelList.length - 1" class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup>
  import { watch, ref, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  const levelList = ref([])
  // 获取当前路由对象
  const route = useRoute()
  const router = useRouter()
  watch(
      () => route.path, // 监听 route.path 的变化
      (newPath, oldPath) => {
        if (newPath.startsWith('/redirect/')) {
          return
        }
        getBreadcrumb()
      }
  )

  // 初始化时获取面包屑
  onMounted(() => {
    getBreadcrumb()
  })

  // 获取面包屑导航数据
  const getBreadcrumb = () => {
    // 过滤出包含 meta.title 的路由记录
    let matched = route.matched

    // 如果第一个路由不是 Dashboard，则手动添加 Dashboard
    if (!isDashboard(matched[0])) {
      matched = [ { path: '/dashboard', meta: { title: 'Dashboard' } } ].concat(matched)
    }

    // 更新 levelList
    levelList.value = matched
  }

  // 判断是否是 Dashboard 路由
  const isDashboard = (route) => {
    return route?.name === 'Dashboard'
  }

  const handleLink = (item) => {
    const { redirect, path } = item
    if (redirect) {
      router.push(redirect)
      return
    }
    router.push(path)
  }
</script>
